import type { MRT_ColumnDef } from 'material-react-table'
import { z } from 'zod'

import { baseManyObjectsScheme, baseSchemeWithNote } from '@/types/base.types'

import { phoneRegex } from '@/config/zod.config'

import { dayjsStrValidator, nullableString } from '@/utils/customValidators'

export const requestsColumns: MRT_ColumnDef<IRequest>[] = [
	{
		header: 'ID',
		accessorKey: 'id',
		size: 100,
		enablePinning: true
	},
	{
		header: 'Имя',
		accessorKey: 'first_name',
		enablePinning: true,
		enableClickToCopy: true
	},
	{
		header: 'Телефон',
		accessorKey: 'phone_number',
		enableClickToCopy: true
	},
	{
		header: 'Статус',
		accessorFn: row => requestStatuses[row.status]
	},
	{
		header: 'Источник',
		accessorFn: row => row.request_service.display_name
	},
	{
		header: 'Дата добавления',
		accessorFn: row => row.created_on.format('HH:mm DD.MM.YYYY')
	},
	{
		header: 'Последнее изменение',
		accessorFn: row => row.updated_on.format('HH:mm DD.MM.YYYY')
	}
]

export const requestStatuses: { [index: number]: string } = {
	0: 'Новая',
	1: 'Первичный чертеж',
	2: 'Замер',
	3: 'Окончательный чертеж',
	4: 'Согласование',
	5: 'Заказ сформирован',
	7: 'Сорвалась',
	8: 'Не настоящая',
	9: 'Завершена'
}

export const requestService = z.object({
	id: z.number(),
	name: z.string(),
	display_name: z.string(),
	created_on: dayjsStrValidator,
	updated_on: dayjsStrValidator
})

export type IRequestService = z.infer<typeof requestService>

export const requestScheme = baseSchemeWithNote.extend({
	first_name: z.string(),
	phone_number: z.string(),
	number_in_program: nullableString,
	changes_history: nullableString,
	status: z.number().min(0).max(9),
	request_service: requestService,
	client: z.number().nullable().default(null),
	tasks: z.number(),
	attachs: z.number()
})

export type IRequest = z.infer<typeof requestScheme>

export const requestFormScheme = z.object({
	first_name: z.string().min(2).max(35),
	phone_number: z.string().regex(phoneRegex, 'Некорректный номер телефона'),
	number_in_program: z.string().nullable(),
	note: z.string(),
	changes_history: z.string().nullable(),
	status: z.coerce.number().min(0).max(9),
	client: z.coerce.number().nullable()
})

export type IRequestForm = z.infer<typeof requestFormScheme>

export const requestsScheme = baseManyObjectsScheme.extend({
	results: z.array(requestScheme)
})

export type IRequests = z.infer<typeof requestsScheme>
